<script lang="ts" setup>
import type { GenericTableApi } from '#/api/lowcode/generic';

import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { useVbenForm, useVbenModal } from '@vben/common-ui';
import { z } from '@vben/common-ui';

import formCreate from '@form-create/ant-design-vue';

// 导入字典相关工具函数
import { getDictOptions, getDictLabel, deleteDictCache } from '#/utils';
// 导入上传工具函数
import { useUpload } from '#/components/upload/use-upload';

interface Props {
  metadata?: GenericTableApi.TableMetadata;
  tableName?: string;
  dataSourceId?: number;
  isEdit?: boolean;
  record?: GenericTableApi.TableData;
}

interface Emits {
  (e: 'confirm', data: GenericTableApi.TableData): void;
}

const props = withDefaults(defineProps<Props>(), {
  isEdit: false,
  dataSourceId: 0,
});

const emit = defineEmits<Emits>();

// 从modal获取数据
const modalData = ref<any>({});

// 强制刷新表单
function forceRefreshForm() {
  const metadata = modalData.value?.metadata || props.metadata;
  if (!metadata) return;
  
  fieldsChanged.value = true;
  
  if (metadata.columns) {
    clearDictionaryCache(metadata.columns);
    preloadDictionaries(metadata.columns);
  }
  
  nextTick(() => {
    rebuildForm();
    fieldsChanged.value = false;
  });
}

// 暴露方法给父组件调用（将在文件末尾合并）
const [Modal, modalApi] = useVbenModal({
  onConfirm: async () => {
    await handleSubmit();
    return true;
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      modalData.value = modalApi.getData() || {};
      
      
      // 表单打开时，主动检查并重建表单（确保最新配置生效）
      nextTick(() => {
        fieldsChanged.value = true; // 标记需要重建
        rebuildForm();
        fieldsChanged.value = false;
        
        // 重建表单后立即设置编辑值
        setTimeout(() => {
          setFormValues();
        }, 100);
      });
    }
  },
});

// form-create实例
const fApi = ref<any>(null);
// 是否使用form-create
const useFormCreate = ref(false);
// 表单规则
const formRules = ref<any[]>([]);
// 字段是否已变化的标志
const fieldsChanged = ref(false);

// VbenForm实例 (fallback)
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'vertical',
  schema: [],
  showDefaultActions: false,
});

// 检查是否有form-create配置
const hasFormCreateConfig = computed(() => {
  const metadata = modalData.value?.metadata || props.metadata;
  if (!metadata?.table?.tableForm) return false;
  
  try {
    const config = JSON.parse(metadata.table.tableForm);
    return config && config.rule && config.rule.length > 0;
  } catch {
    return false;
  }
});

// ========== 字典相关工具函数 ==========

// 判断字段是否需要字典支持
function isDictField(column: any): boolean {
  const htmlType = column.htmlType || '';
  return ['select', 'radio', 'checkbox'].includes(htmlType) && !!column.dictType;
}

// 获取字典选项列表（用于表单）
function getDictSelectOptions(dictType: string) {
  if (!dictType) return [];
  
  try {
    return getDictOptions(dictType).map(option => ({
      label: option.label,
      value: option.value
    }));
  } catch (error) {
    console.warn(`字典选项获取失败: ${dictType}`, error);
    return [];
  }
}

// 设置表单值的统一方法
function setFormValues() {
  const record = modalData.value?.record;
  const isEdit = modalData.value?.isEdit;
  const metadata = modalData.value?.metadata;
  
  if (record && isEdit && metadata) {
    const values = processFormValues(record, metadata);
    
    if (useFormCreate.value && fApi.value) {
      try {
        // 先重置表单，避免脏数据
        fApi.value.resetFields();
        
        // 延迟设置值，确保表单完全初始化
        setTimeout(() => {
          fApi.value.setValue(values);
          
          // 再次确认设置，确保字典值正确显示
          setTimeout(() => {
            fApi.value.setValue(values);
          }, 100);
        }, 50);
      } catch (error) {
        console.error('form-create设置值失败:', error);
      }
    } else if (formApi) {
      try {
        formApi.resetForm();
        setTimeout(() => {
          formApi.setValues(values);
        }, 50);
      } catch (error) {
        console.error('VbenForm设置值失败:', error);
      }
    }
  } else if (!isEdit) {
    // 新增模式下重置表单
    if (useFormCreate.value && fApi.value) {
      fApi.value.resetFields();
    } else if (formApi) {
      formApi.resetForm();
    }
  }
}

// 处理表单值，特别是日期格式转换
function processFormValues(record: any, metadata: any) {
  if (!record || !metadata?.columns) return { ...record };
  
  const values = { ...record };
  
  metadata.columns.forEach((col: any) => {
    const field = col.javaField || col.field || col.columnName;
    const javaType = col.javaType || '';
    const jdbcType = (col.jdbcType || col.columnType || '').toLowerCase();
    
    
    // 处理日期字段
    if (values[field] !== null && values[field] !== undefined && (javaType === 'LocalDateTime' || javaType === 'LocalDate' || jdbcType.includes('datetime') || jdbcType.includes('timestamp') || jdbcType.includes('date'))) {
      try {
        let dateValue: Date | null = null;
        
        if (typeof values[field] === 'number') {
          // 时间戳处理 - 优先处理，因为后端返回时间戳
          dateValue = new Date(values[field]);
        } else if (typeof values[field] === 'string' && values[field].trim()) {
          // 字符串格式的日期处理
          if (values[field].includes('T')) {
            // ISO格式: 2023-10-01T10:30:00Z 或 2023-10-01T10:30:00.000Z
            dateValue = new Date(values[field]);
          } else if (values[field].includes(' ')) {
            // 格式: 2023-10-01 10:30:00
            dateValue = new Date(values[field].replace(' ', 'T'));
          } else if (/^\d{4}-\d{2}-\d{2}$/.test(values[field])) {
            // 格式: 2023-10-01
            dateValue = new Date(values[field] + 'T00:00:00');
          } else {
            // 尝试直接解析
            dateValue = new Date(values[field]);
          }
        }
        
        // 验证日期是否有效并设置最终值
        if (dateValue && !isNaN(dateValue.getTime())) {
          // 根据字段类型决定最终格式
          if (javaType === 'LocalDate' || (jdbcType.includes('date') && !jdbcType.includes('datetime') && !jdbcType.includes('timestamp'))) {
            // 纯日期字段，使用YYYY-MM-DD格式字符串
            const year = dateValue.getFullYear();
            const month = String(dateValue.getMonth() + 1).padStart(2, '0');
            const day = String(dateValue.getDate()).padStart(2, '0');
            values[field] = `${year}-${month}-${day}`;
          } else {
            // 日期时间字段，form-create的DatePicker可能需要特定格式
            // 尝试使用字符串格式，因为有些DatePicker更兼容字符串
            const dateTimeStr = dateValue.getFullYear() + '-' + 
                               String(dateValue.getMonth() + 1).padStart(2, '0') + '-' + 
                               String(dateValue.getDate()).padStart(2, '0') + ' ' +
                               String(dateValue.getHours()).padStart(2, '0') + ':' +
                               String(dateValue.getMinutes()).padStart(2, '0') + ':' +
                               String(dateValue.getSeconds()).padStart(2, '0');
            
            // 使用字符串格式（更兼容）
            values[field] = dateTimeStr;
          }
        } else {
          console.warn(`❌ 日期字段 ${field} 转换失败，原始值:`, values[field]);
          values[field] = null;
        }
      } catch (error) {
        console.warn(`日期字段 ${field} 处理失败:`, error, values[field]);
        values[field] = null;
      }
    }
    
    // 处理数字字段
    if (values[field] !== null && values[field] !== undefined && (javaType === 'Integer' || javaType === 'Long' || jdbcType.includes('int') || jdbcType.includes('decimal'))) {
      if (typeof values[field] === 'string' && values[field] !== '') {
        values[field] = Number(values[field]);
      }
    }
    
    // 处理布尔字段
    if (values[field] !== null && values[field] !== undefined && (javaType === 'Boolean' || jdbcType.includes('bit'))) {
      if (typeof values[field] === 'string') {
        values[field] = values[field] === 'true' || values[field] === '1';
      } else if (typeof values[field] === 'number') {
        values[field] = values[field] === 1;
      }
    }
    
    // 特殊处理：字典字段的值类型匹配
    if (col && isDictField(col)) {
      const dictOptions = getDictSelectOptions(col.dictType);
      if (dictOptions.length > 0) {
        const currentValue = values[field];
        
        // 查找匹配的选项
        let matchedOption = dictOptions.find(opt => opt.value === currentValue);
        
        // 如果没有找到完全匹配，尝试类型转换匹配
        if (!matchedOption && currentValue !== null && currentValue !== undefined) {
          // 尝试字符串匹配
          const stringValue = String(currentValue);
          matchedOption = dictOptions.find(opt => String(opt.value) === stringValue);
          
          if (matchedOption) {
            values[field] = matchedOption.value;
          } else {
            // 尝试布尔值特殊处理
            if (typeof currentValue === 'boolean') {
              const boolStr = currentValue ? 'true' : 'false';
              const boolNum = currentValue ? 1 : 0;
              matchedOption = dictOptions.find(opt => 
                String(opt.value) === boolStr || 
                opt.value === boolNum ||
                (currentValue === true && (opt.value === '1' || opt.value === 1)) ||
                (currentValue === false && (opt.value === '0' || opt.value === 0))
              );
              
              if (matchedOption) {
                values[field] = matchedOption.value;
              }
            }
          }
        }
      }
    }
    
    // 特殊处理：上传字段的值格式转换
    if (col && (col.htmlType === 'imageUpload' || col.htmlType === 'fileUpload')) {
      const currentValue = values[field];
      
      if (currentValue === null || currentValue === undefined) {
        // 空值，设置为空数组
        values[field] = [];
      } else if (typeof currentValue === 'string') {
        if (currentValue.trim() === '') {
          // 空字符串，设置为空数组
          values[field] = [];
        } else if (!currentValue.startsWith('[') && !currentValue.startsWith('{')) {
          // 简单的URL字符串，根据form-create文档，value应该是URL字符串数组
          values[field] = [currentValue];
        } else {
          // 尝试解析JSON字符串
          try {
            const parsed = JSON.parse(currentValue);
            if (Array.isArray(parsed)) {
              // 数组格式，提取URL字符串
              values[field] = parsed.map(item => 
                typeof item === 'string' ? item : (item.url || item)
              );
            } else {
              // 单个值，转换为数组
              const url = typeof parsed === 'string' ? parsed : (parsed.url || parsed);
              values[field] = [url];
            }
          } catch (error) {
            // 解析失败，当作普通URL字符串处理
            values[field] = [currentValue];
          }
        }
      } else if (Array.isArray(currentValue)) {
        // 已经是数组格式，确保格式正确
        // 数组格式，确保是URL字符串数组
        values[field] = currentValue.map(item => {
          if (typeof item === 'string') {
            return item;
          } else if (item && typeof item === 'object' && item.url) {
            return item.url;
          } else {
            return item;
          }
        });
      } else {
        // 其他类型，设置为空数组
        values[field] = [];
      }
    }
  });
  
  return values;
}

// 批量预加载字典数据
function preloadDictionaries(columns: any[]) {
  if (!columns) return;
  
  const dictTypes = columns
    .filter(isDictField)
    .map(col => col.dictType)
    .filter(Boolean);
  
  // 触发字典数据缓存加载
  dictTypes.forEach(dictType => {
    try {
      getDictOptions(dictType);
    } catch (error) {
      console.warn(`字典加载失败: ${dictType}`, error);
    }
  });
}

// 清理字典缓存
function clearDictionaryCache(columns: any[]) {
  if (!columns) return;
  
  const dictTypes = columns
    .filter(isDictField)
    .map(col => col.dictType)
    .filter(Boolean);
  
  // 清理特定字典类型的缓存
  dictTypes.forEach(dictType => {
    try {
      deleteDictCache(dictType);
    } catch (error) {
      console.warn(`字典缓存清理失败: ${dictType}`, error);
    }
  });
}

// 解析form-create配置
function parseFormCreateConfig() {
  if (!hasFormCreateConfig.value) return [];
  
  try {
    const metadata = modalData.value?.metadata || props.metadata;
    const config = JSON.parse(metadata!.table!.tableForm!);
    let rules = config.rule || [];
    
    
    // 为字典字段动态添加选项，同时修正上传组件配置
    rules = rules.map((rule: any) => {
      // 找到对应的列配置
      const column = metadata?.columns?.find(col => {
        const fieldName = col.javaField || col.field || col.columnName;
        return fieldName === rule.field;
      });
      
      if (column && isDictField(column)) {
        const dictOptions = getDictSelectOptions(column.dictType);
        
        // 更新规则的选项
        return {
          ...rule,
          options: dictOptions
        };
      }
      
      // 修正上传组件 - 使用customRequest处理认证并提取URL
      if (rule.type === 'upload') {
        
        const modifiedRule = {
          ...rule,
          props: {
            ...rule.props,
            // 完全替换为customRequest，不使用action
            action: undefined,
            // 添加必需的onSuccess（即使用不到，form-create需要这个属性）
            onSuccess: function() {
              // 空函数，实际处理在customRequest中
            },
            onError: function() {
              // 空函数，实际处理在customRequest中  
            },
            customRequest: async function(info: any) {
              try {
                // 使用框架的上传方法，会自动处理认证
                const uploadApi = useUpload().httpRequest;
                const result = await uploadApi(info.file);
                
                // 提取URL - 支持多种返回格式
                let url = null;
                if (typeof result === 'string') {
                  // 直接返回URL字符串
                  url = result;
                } else if (result && result.url) {
                  // 对象格式: { url: "..." }
                  url = result.url;
                } else if (result && result.data) {
                  // 对象格式: { data: "..." }
                  url = result.data;
                }
                
                if (url) {
                  // 设置file属性，让upload组件正确显示
                  info.file.url = url;
                  info.file.status = 'done';
                  info.file.response = { code: 0, data: url };
                  info.file.percent = 100;
                  
                  // 立即更新表单字段值
                  if (fApi.value) {
                    fApi.value.setValue(rule.field, url);
                  }
                  
                  // 调用成功回调
                  info.onSuccess({ code: 0, data: url }, info.file);
                } else {
                  info.onError(new Error('上传返回结果格式不正确'));
                }
              } catch (error) {
                info.onError(error);
              }
            }
          }
        };
        
        return modifiedRule;
      }
      
      return rule;
    });
    return rules;
  } catch (error) {
    console.warn('解析表单配置失败:', error);
    return [];
  }
}

// 监听metadata变化
watch(
  [() => modalData.value?.metadata, () => props.metadata],
  (newValues, oldValues) => {
    const currentMetadata = modalData.value?.metadata || props.metadata;
    const oldMetadata = oldValues?.[0] || oldValues?.[1];
    
    if (!currentMetadata) return;
    
    const hasChanged = !oldMetadata || 
      JSON.stringify(currentMetadata.columns) !== JSON.stringify(oldMetadata.columns);
    
    if (hasChanged) {
      if (oldMetadata?.columns) {
        clearDictionaryCache(oldMetadata.columns);
      }
      
      if (currentMetadata.columns) {
        preloadDictionaries(currentMetadata.columns);
      }
      
      fieldsChanged.value = true;
      nextTick(() => {
        rebuildForm();
        fieldsChanged.value = false;
      });
    }
  },
  { immediate: true, deep: true }
);

// 重建表单的统一方法
function rebuildForm() {
  const currentMetadata = modalData.value?.metadata || props.metadata;
  if (!currentMetadata) {
    return;
  }
  
  if (hasFormCreateConfig.value) {
    useFormCreate.value = true;
    const rules = parseFormCreateConfig();
    
    // 强制更新form-create规则
    formRules.value = [...rules]; // 使用展开运算符确保响应式更新
    
    if (fApi.value) {
      nextTick(() => {
        try {
          fApi.value.updateRules(rules);
          
          // 规则更新完成后再设置表单值
          setTimeout(() => {
            setFormValues();
          }, 50);
        } catch (error) {
          console.error('form-create规则更新失败:', error);
        }
      });
    }
  } else {
    useFormCreate.value = false;
    const schema = generateFormSchema();
    
    if (schema.length > 0) {
      try {
        formApi.updateSchema(schema);
      } catch (error) {
        console.error('VbenForm schema更新失败:', error);
      }
    }
  }
}

// 原有的动态生成表单schema逻辑
function generateFormSchema() {
  const metadata = modalData.value?.metadata || props.metadata;
  if (!metadata) return [];
  
  const isEdit = modalData.value?.isEdit ?? props.isEdit;
  
  return metadata.columns
    .filter(col => {
      // 过滤逻辑：
      // 1. 主键字段在新增时显示，编辑时隐藏
      if (col.primaryKey) {
        return !isEdit;
      }
      // 2. 只显示可编辑的字段
      return col.editable;
    })
    .map(col => {
      const field = col.javaField || col.field || col.columnName;
      const required = !col.nullable && !col.primaryKey;
      
      // 基础配置
      const baseConfig = {
        fieldName: field,
        label: col.title || col.displayName || col.columnComment || col.columnName,
        required,
        rules: required ? z.string().min(1, '此字段为必填项') : z.string().optional(),
      };
      
      // 根据数据类型选择组件
      const javaType = col.javaType || '';
      const jdbcType = (col.jdbcType || col.columnType || '').toLowerCase();
      
      if (col.dictType) {
        // 字典类型
        const dictOptions = getDictSelectOptions(col.dictType);
        return {
          ...baseConfig,
          component: 'Select',
          componentProps: {
            placeholder: `请选择${baseConfig.label}`,
            allowClear: true,
            options: dictOptions,
          },
        };
      } else if (jdbcType.includes('text') || jdbcType.includes('longtext')) {
        // 长文本
        return {
          ...baseConfig,
          component: 'Textarea',
          componentProps: {
            placeholder: `请输入${baseConfig.label}`,
            rows: 4,
          },
        };
      } else if (javaType === 'LocalDateTime' || jdbcType.includes('datetime') || jdbcType.includes('timestamp')) {
        // 日期时间类型
        const isDateTime = javaType === 'LocalDateTime' || jdbcType.includes('datetime') || jdbcType.includes('timestamp');
        return {
          ...baseConfig,
          component: isDateTime ? 'DatePicker' : 'DatePicker',
          componentProps: {
            placeholder: `请选择${baseConfig.label}`,
            showTime: isDateTime,
            format: isDateTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD',
            valueFormat: isDateTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD',
          },
        };
      } else if (javaType === 'Long' || javaType === 'Integer' || javaType === 'Object' || jdbcType.includes('int') || jdbcType.includes('decimal') || jdbcType.includes('float') || jdbcType.includes('tinyint')) {
        // 数字类型
        return {
          ...baseConfig,
          component: 'InputNumber',
          componentProps: {
            placeholder: `请输入${baseConfig.label}`,
            style: { width: '100%' },
          },
          rules: required 
            ? z.number({ required_error: '此字段为必填项' })
            : z.number().optional(),
        };
      } else if (javaType === 'Boolean' || jdbcType.includes('bit')) {
        // 布尔类型
        return {
          ...baseConfig,
          component: 'Switch',
          componentProps: {
            checkedChildren: '是',
            unCheckedChildren: '否',
          },
          rules: z.boolean().optional(),
        };
      } else {
        // 默认文本输入
        return {
          ...baseConfig,
          component: 'Input',
          componentProps: {
            placeholder: `请输入${baseConfig.label}`,
          },
        };
      }
    });
}

// 监听记录变化，设置表单值（简化版本，避免重复设置）
watch(
  [() => modalData.value?.record, () => props.record, () => modalData.value?.isEdit, () => props.isEdit],
  () => {
    // 延迟设置表单值，避免与表单重建冲突
    setTimeout(() => {
      setFormValues();
    }, 100);
  },
  { immediate: false } // 不立即执行，避免与onOpenChange冲突
);

// 时间格式化工具函数
function formatDateTime(timestamp: any): string | null {
  if (!timestamp) return null;
  
  try {
    let date: Date;
    
    if (timestamp instanceof Date) {
      date = timestamp;
    } else if (typeof timestamp === 'number') {
      date = new Date(timestamp);
    } else if (typeof timestamp === 'string') {
      date = new Date(timestamp);
    } else {
      return null;
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return null;
    }
    
    // 格式化为 yyyy-MM-dd HH:mm:ss
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.warn('时间格式化失败:', error);
    return null;
  }
}

// 日期格式化工具函数（仅日期）
function formatDate(timestamp: any): string | null {
  if (!timestamp) return null;
  
  try {
    let date: Date;
    
    if (timestamp instanceof Date) {
      date = timestamp;
    } else if (typeof timestamp === 'number') {
      date = new Date(timestamp);
    } else if (typeof timestamp === 'string') {
      date = new Date(timestamp);
    } else {
      return null;
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return null;
    }
    
    // 格式化为 yyyy-MM-dd
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  } catch (error) {
    console.warn('日期格式化失败:', error);
    return null;
  }
}

// 提交表单
async function handleSubmit() {
  try {
    let formData: any;
    
    if (useFormCreate.value && fApi.value) {
      // form-create表单验证和获取值
      const valid = await fApi.value.validate();
      if (!valid) return;
      formData = fApi.value.formData();
    } else {
      // VbenForm表单验证和获取值
      const valid = await formApi.validate();
      if (!valid) return;
      formData = formApi.getValues();
    }
    
    // 处理时间字段和上传字段格式转换
    const metadata = modalData.value?.metadata || props.metadata;
    if (metadata) {
      metadata.columns.forEach(col => {
        const field = col.javaField || col.field || col.columnName;
        const javaType = col.javaType || '';
        const jdbcType = (col.jdbcType || col.columnType || '').toLowerCase();
        
        if (formData[field]) {
          if (javaType === 'LocalDateTime' || jdbcType.includes('datetime') || jdbcType.includes('timestamp')) {
            // 日期时间字段：转换为 yyyy-MM-dd HH:mm:ss
            formData[field] = formatDateTime(formData[field]);
          } else if (javaType === 'LocalDate' || jdbcType.includes('date')) {
            // 日期字段：转换为 yyyy-MM-dd
            formData[field] = formatDate(formData[field]);
          }
        }
        
        // 上传字段：将URL数组格式转换回字符串格式
        if (col.htmlType === 'imageUpload' || col.htmlType === 'fileUpload') {
          if (Array.isArray(formData[field])) {
            if (formData[field].length === 1) {
              // 单个文件，直接使用URL字符串
              formData[field] = formData[field][0];
            } else if (formData[field].length > 1) {
              // 多个文件，转换为JSON字符串
              formData[field] = JSON.stringify(formData[field]);
            } else {
              // 空数组，设置为null
              formData[field] = null;
            }
          }
        }
      });
    }
    
    // 调用 modalData 中的 onConfirm 回调
    if (modalData.value?.onConfirm) {
      await modalData.value.onConfirm(formData);
    } else {
      emit('confirm', formData);
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  }
}

// 重置表单
function handleReset() {
  if (useFormCreate.value && fApi.value) {
    fApi.value.resetFields();
  } else {
    formApi.resetForm();
  }
}

defineExpose({
  forceRefreshForm,
  submit: handleSubmit,
  reset: handleReset,
});
</script>

<template>
  <Modal :title="modalData?.title" :fullscreen-button="false">
    <div class="p-4">
      <!-- 使用form-create表单 -->
      <div v-if="useFormCreate">
        <form-create 
          v-model:api="fApi"
          :rule="formRules"
          :option="{
            form: { labelCol: { span: 6 }, wrapperCol: { span: 18 } },
            submitBtn: false,
            resetBtn: false,
          }"
        />
      </div>
      
      <!-- 使用VbenForm表单 (fallback) -->
      <Form v-else />
    </div>
  </Modal>
</template>